package com.wavefront.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import com.wavefront.Model;
import com.wavefront.obj.parser.LineParser;
import com.wavefront.obj.parser.ObjParser;

public final class ObjLoader {

	public static void load(
			String fileName, Model contextModel)
	{
		String contextFolder = "";
		ObjParser.currentModel = contextModel;

		int lastSlashIndex = fileName.lastIndexOf('/');
		if (lastSlashIndex != -1)
			contextFolder = fileName.substring(0, lastSlashIndex + 1);

		lastSlashIndex = fileName.lastIndexOf('\\');
		if (lastSlashIndex != -1)
			contextFolder = fileName.substring(0, lastSlashIndex + 1);

		ObjParser.setCurrentFolder(contextFolder);
		
		try {

			File file = new File(fileName);
			FileInputStream fileInput;

			if (file.exists()) {
				fileInput = new FileInputStream(file);

				BufferedReader in = null;

				in = new BufferedReader(new InputStreamReader(fileInput));

				String currentLine = null;
				while ((currentLine = in.readLine()) != null) {
					if (!"".equals(currentLine)) {
						currentLine = currentLine.replaceAll("  ", " ");
						currentLine = currentLine.replaceAll("	", "");
						String[] lineWords = currentLine.split(" ");
						String lineType = lineWords[0];
						LineParser parser = ObjParser.getLineParser(lineType);
						parser.parse(lineWords);
					}
				}

				if (in != null)
					in.close();

			}
			;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("Error reading file :'" + fileName + "'");
		}

	}
}
